package kt_test.util

import android.content.Context
import android.os.Environment
import android.util.Log
import com.google.gson.Gson
import kt_test.room.entity.OxygenSampleEntity
import java.io.File
import java.io.FileWriter
import java.text.SimpleDateFormat
import java.util.*

object OxygenExportUtil {

    fun exportToJson(context: Context, userId: String, samples: List<OxygenSampleEntity>): String? {
        return try {
            val gson = Gson()
            val jsonString = gson.toJson(samples)

            val exportDir = File(context.getExternalFilesDir(null), "oxygen_export")
            if (!exportDir.exists()) exportDir.mkdirs()

            val timestamp = SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(Date())
            val fileName = "spo2_export_${userId}_$timestamp.json"
            val file = File(exportDir, fileName)

            FileWriter(file).use { it.write(jsonString) }

            Log.d("OxygenExport", "导出成功: ${file.absolutePath}")
            file.absolutePath
        } catch (e: Exception) {
            Log.e("OxygenExport", "导出失败: ${e.message}")
            null
        }
    }

    fun exportToCsv(context: Context, userId: String, samples: List<OxygenSampleEntity>): String? {
        return try {
            val exportDir = File(context.getExternalFilesDir(null), "oxygen_export")
            if (!exportDir.exists()) exportDir.mkdirs()

            val timestamp = SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(Date())
            val fileName = "spo2_export_${userId}_$timestamp.csv"
            val file = File(exportDir, fileName)

            FileWriter(file).use { writer ->
                writer.append("用户ID,时间,血氧值(%)\n")  // 表头
                for (sample in samples) {
                    writer.append("${sample.userId},${sample.time},${sample.spo2}\n")
                }
            }

            Log.d("OxygenExport", "CSV 导出成功: ${file.absolutePath}")
            file.absolutePath
        } catch (e: Exception) {
            Log.e("OxygenExport", "CSV 导出失败: ${e.message}")
            null
        }
    }

}
